<?php

namespace Admin\Controller;

use Think\Log;

class MapController
{
    private $ak = 'cAdlwxedBYGjWRTIL1IpG8omYOxfYZvW';

    /**
     * 通过地址查询经纬度
     */
    public function getLnglatByAddress()
    {
        $ak = $this->ak;
        $address = I('address');
        try {
            $url = 'http://api.map.baidu.com/geocoder/v2/?address=' . $address . '&output=json&ak=' . $ak;
            $ret = file_get_contents($url);
            $ret = json_decode($ret, true);
            if ($ret['status'] == 0) {
                exit(json_encode($ret['result']['location']));
            } else {
                exit(json_encode(['lng' => 0, 'lat' => 0]));
            }
        } catch (\Exception $e) {
            Log::write('百度地图获取地址抛出异常：' . $e->getMessage() . '----' . $e->getCode());
            exit(json_encode(['lng' => 0, 'lat' => 0]));
        }
    }

    /**
     * 通过经纬度获取地址信息
     */
    public function getAddressByLnglat()
    {
        $ak = $this->ak;
        $lat = I('lat');
        $lng = I('lng');
        try {
            //$url = 'http://api.map.baidu.com/geocoder/v2/?ak=' . $ak . '&callback=renderReverse&location=' . $lat . ',' . $lng . '&output=json&pois=1';
            $url = 'http://api.map.baidu.com/geocoder/v2/?ak=' . $ak . '&location=' . $lat . ',' . $lng . '&output=json&pois=1';
            $ret = file_get_contents($url);
            $ret = json_decode($ret, true);
            if ($ret['status'] == 0) {
                exit(json_encode(['address' => $ret['result']['formatted_address']]));
            } else {
                exit(json_encode(['address' => '']));
            }
        } catch (\Exception $e) {
            Log::write('百度地图获取经纬度抛出异常：' . $e->getMessage() . '----' . $e->getCode());
            exit(json_encode(['address' => '']));
        }
    }
}